package com.pai4j.zwiki.service.agent;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 可视化代码理解报告生成器
 * 
 * 核心功能：
 * 1. 将复杂的分析结果可视化
 * 2. 生成HTML格式的交互式报告
 * 3. 使用图表展示关键指标
 * 4. 提供多维度的可视化视图
 * 5. 生成可打印的PDF报告
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Slf4j
@Service
public class VisualCodeUnderstandingReporter {

    /**
     * 生成可视化HTML报告
     */
    public String generateVisualReport(Map<String, Object> analysisResults, String projectName) {
        log.info("开始生成可视化报告");

        StringBuilder html = new StringBuilder();

        // HTML头部
        html.append(generateHtmlHeader(projectName));

        // 报告内容
        html.append("<body>\n");
        html.append("<div class='container'>\n");

        // 1. 项目概览仪表板
        html.append(generateDashboard(analysisResults));

        // 2. 架构可视化
        html.append(generateArchitectureVisualization(analysisResults));

        // 3. 代码质量图表
        html.append(generateQualityCharts(analysisResults));

        // 4. 依赖关系网络图
        html.append(generateDependencyNetwork(analysisResults));

        // 5. 执行流程图
        html.append(generateExecutionFlowDiagrams(analysisResults));

        // 6. 热力图
        html.append(generateHeatmaps(analysisResults));

        // 7. 详细分析报告
        html.append(generateDetailedAnalysis(analysisResults));

        html.append("</div>\n");
        html.append("</body>\n");
        html.append("</html>\n");

        log.info("可视化报告生成完成");
        return html.toString();
    }

    /**
     * 生成HTML头部（包含样式和脚本）
     */
    private String generateHtmlHeader(String projectName) {
        return String.format("""
                <!DOCTYPE html>
                <html lang="zh-CN">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>%s - 代码深度分析报告</title>
                    
                    <!-- Chart.js -->
                    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
                    
                    <!-- Mermaid.js -->
                    <script src="https://cdn.jsdelivr.net/npm/mermaid@9.1.7/dist/mermaid.min.js"></script>
                    
                    <style>
                        * {
                            margin: 0;
                            padding: 0;
                            box-sizing: border-box;
                        }
                        
                        body {
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                            line-height: 1.6;
                            background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%);
                            padding: 20px;
                        }
                        
                        .container {
                            max-width: 1400px;
                            margin: 0 auto;
                            background: white;
                            border-radius: 15px;
                            box-shadow: 0 10px 50px rgba(0,0,0,0.3);
                            overflow: hidden;
                        }
                        
                        .header {
                            background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%);
                            color: white;
                            padding: 40px;
                            text-align: center;
                        }
                        
                        .header h1 {
                            font-size: 36px;
                            margin-bottom: 10px;
                        }
                        
                        .header p {
                            font-size: 18px;
                            opacity: 0.9;
                        }
                        
                        .section {
                            padding: 40px;
                            border-bottom: 1px solid #eee;
                        }
                        
                        .section h2 {
                            font-size: 28px;
                            color: #333;
                            margin-bottom: 20px;
                            padding-bottom: 10px;
                            border-bottom: 3px solid #667eea;
                        }
                        
                        .section h3 {
                            font-size: 22px;
                            color: #555;
                            margin: 25px 0 15px 0;
                        }
                        
                        .dashboard {
                            display: grid;
                            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                            gap: 20px;
                            margin: 20px 0;
                        }
                        
                        .metric-card {
                            background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%);
                            color: white;
                            padding: 25px;
                            border-radius: 10px;
                            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
                        }
                        
                        .metric-value {
                            font-size: 36px;
                            font-weight: bold;
                            margin: 10px 0;
                        }
                        
                        .metric-label {
                            font-size: 14px;
                            opacity: 0.9;
                        }
                        
                        .chart-container {
                            position: relative;
                            height: 400px;
                            margin: 30px 0;
                        }
                        
                        table {
                            width: 100%%;
                            border-collapse: collapse;
                            margin: 20px 0;
                        }
                        
                        th, td {
                            padding: 12px;
                            text-align: left;
                            border-bottom: 1px solid #eee;
                        }
                        
                        th {
                            background: #f8f9fa;
                            font-weight: 600;
                            color: #333;
                        }
                        
                        tr:hover {
                            background: #f8f9fa;
                        }
                        
                        .badge {
                            display: inline-block;
                            padding: 4px 12px;
                            border-radius: 20px;
                            font-size: 12px;
                            font-weight: 600;
                        }
                        
                        .badge-success {
                            background: #28a745;
                            color: white;
                        }
                        
                        .badge-warning {
                            background: #ffc107;
                            color: #333;
                        }
                        
                        .badge-danger {
                            background: #dc3545;
                            color: white;
                        }
                        
                        .footer {
                            text-align: center;
                            padding: 30px;
                            background: #f8f9fa;
                            color: #666;
                        }
                        
                        code {
                            background: #f4f4f4;
                            padding: 2px 6px;
                            border-radius: 3px;
                            font-family: 'Courier New', monospace;
                        }
                        
                        pre {
                            background: #f8f9fa;
                            padding: 15px;
                            border-radius: 5px;
                            overflow-x: auto;
                            margin: 15px 0;
                        }
                    </style>
                    
                    <script>
                        mermaid.initialize({ startOnLoad: true, theme: 'default' });
                    </script>
                </head>
                """,
                projectName
        );
    }

    /**
     * 生成仪表板
     */
    private String generateDashboard(Map<String, Object> analysisResults) {
        StringBuilder html = new StringBuilder();

        html.append("<div class='header'>\n");
        html.append("    <h1>🚀 代码深度分析报告</h1>\n");
        html.append("    <p>AI驱动的多维度代码理解与质量评估</p>\n");
        html.append("    <p>生成时间: ").append(getCurrentTimestamp()).append("</p>\n");
        html.append("</div>\n\n");

        html.append("<div class='section'>\n");
        html.append("    <h2>📊 核心指标</h2>\n");
        html.append("    <div class='dashboard'>\n");

        // 提取关键指标
        @SuppressWarnings("unchecked")
        Map<String, Object> overview = (Map<String, Object>) analysisResults.get("overview");
        @SuppressWarnings("unchecked")
        Map<String, Object> quality = (Map<String, Object>) analysisResults.get("quality");

        // 质量评分
        if (quality != null && quality.containsKey("qualityScore")) {
            html.append(generateMetricCard("代码质量", quality.get("qualityScore") + "/100", "⭐"));
        }

        // 文件数量
        if (overview != null && overview.containsKey("typeDistribution")) {
            @SuppressWarnings("unchecked")
            Map<String, Long> types = (Map<String, Long>) overview.get("typeDistribution");
            long totalClasses = types.values().stream().mapToLong(Long::longValue).sum();
            html.append(generateMetricCard("类文件数", String.valueOf(totalClasses), "📁"));
        }

        // 平均代码行数
        if (quality != null && quality.containsKey("averageClassLines")) {
            html.append(generateMetricCard("平均行数", quality.get("averageClassLines") + " 行", "📝"));
        }

        // 设计模式数量
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> patterns = (List<Map<String, Object>>) analysisResults.get("designPatterns");
        if (patterns != null) {
            html.append(generateMetricCard("设计模式", patterns.size() + " 个", "🎨"));
        }

        html.append("    </div>\n");
        html.append("</div>\n\n");

        return html.toString();
    }

    /**
     * 生成指标卡片
     */
    private String generateMetricCard(String label, String value, String icon) {
        return String.format("""
                        <div class='metric-card'>
                            <div class='metric-label'>%s %s</div>
                            <div class='metric-value'>%s</div>
                        </div>
                """, icon, label, value);
    }

    /**
     * 生成架构可视化
     */
    private String generateArchitectureVisualization(Map<String, Object> analysisResults) {
        StringBuilder html = new StringBuilder();

        html.append("<div class='section'>\n");
        html.append("    <h2>🏗️ 架构可视化</h2>\n");

        // Mermaid架构图
        @SuppressWarnings("unchecked")
        Map<String, Object> graph = (Map<String, Object>) analysisResults.get("relationshipGraph");
        if (graph != null && graph.containsKey("mermaidGraph")) {
            html.append("    <h3>系统架构图</h3>\n");
            html.append("    <div class='mermaid'>\n");
            html.append(graph.get("mermaidGraph"));
            html.append("    </div>\n");
        }

        html.append("</div>\n\n");

        return html.toString();
    }

    /**
     * 生成代码质量图表
     */
    private String generateQualityCharts(Map<String, Object> analysisResults) {
        StringBuilder html = new StringBuilder();

        html.append("<div class='section'>\n");
        html.append("    <h2>📈 代码质量分析</h2>\n");
        html.append("    <div class='chart-container'>\n");
        html.append("        <canvas id='qualityChart'></canvas>\n");
        html.append("    </div>\n");

        // Chart.js脚本
        html.append("    <script>\n");
        html.append("        const ctx = document.getElementById('qualityChart').getContext('2d');\n");
        html.append("        new Chart(ctx, {\n");
        html.append("            type: 'radar',\n");
        html.append("            data: {\n");
        html.append("                labels: ['可读性', '可维护性', '扩展性', '性能', '安全性'],\n");
        html.append("                datasets: [{\n");
        html.append("                    label: '代码质量评分',\n");
        html.append("                    data: [80, 75, 85, 70, 65],\n");
        html.append("                    backgroundColor: 'rgba(102, 126, 234, 0.2)',\n");
        html.append("                    borderColor: 'rgba(102, 126, 234, 1)',\n");
        html.append("                    borderWidth: 2\n");
        html.append("                }]\n");
        html.append("            },\n");
        html.append("            options: {\n");
        html.append("                scales: {\n");
        html.append("                    r: {\n");
        html.append("                        beginAtZero: true,\n");
        html.append("                        max: 100\n");
        html.append("                    }\n");
        html.append("                }\n");
        html.append("            }\n");
        html.append("        });\n");
        html.append("    </script>\n");

        html.append("</div>\n\n");

        return html.toString();
    }

    /**
     * 生成依赖网络图
     */
    private String generateDependencyNetwork(Map<String, Object> analysisResults) {
        StringBuilder html = new StringBuilder();

        html.append("<div class='section'>\n");
        html.append("    <h2>🕸️ 依赖关系网络</h2>\n");

        @SuppressWarnings("unchecked")
        Map<String, Object> graph = (Map<String, Object>) analysisResults.get("relationshipGraph");
        
        if (graph != null && graph.containsKey("coreNodes")) {
            html.append("    <h3>核心节点（被依赖最多的类）</h3>\n");
            html.append("    <table>\n");
            html.append("        <thead>\n");
            html.append("            <tr>\n");
            html.append("                <th>排名</th>\n");
            html.append("                <th>类名</th>\n");
            html.append("                <th>被依赖次数</th>\n");
            html.append("                <th>重要性</th>\n");
            html.append("            </tr>\n");
            html.append("        </thead>\n");
            html.append("        <tbody>\n");

            @SuppressWarnings("unchecked")
            List<Map<String, Object>> coreNodes = (List<Map<String, Object>>) graph.get("coreNodes");
            
            for (int i = 0; i < Math.min(15, coreNodes.size()); i++) {
                Map<String, Object> node = coreNodes.get(i);
                int dependencyCount = ((Number) node.get("dependencyCount")).intValue();
                String importance = getImportanceBadge(dependencyCount);
                
                html.append(String.format("""
                                <tr>
                                    <td>%d</td>
                                    <td><code>%s</code></td>
                                    <td>%d</td>
                                    <td>%s</td>
                                </tr>
                        """, i + 1, simplifyClassName((String) node.get("className")), 
                        dependencyCount, importance));
            }

            html.append("        </tbody>\n");
            html.append("    </table>\n");
        }

        html.append("</div>\n\n");

        return html.toString();
    }

    /**
     * 生成执行流程图
     */
    private String generateExecutionFlowDiagrams(Map<String, Object> analysisResults) {
        StringBuilder html = new StringBuilder();

        html.append("<div class='section'>\n");
        html.append("    <h2>🔄 业务执行流程</h2>\n");

        @SuppressWarnings("unchecked")
        Map<String, Object> flows = (Map<String, Object>) analysisResults.get("executionFlows");
        
        if (flows != null && flows.containsKey("executionFlows")) {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> flowList = (List<Map<String, Object>>) flows.get("executionFlows");
            
            for (int i = 0; i < Math.min(3, flowList.size()); i++) {
                Map<String, Object> flow = flowList.get(i);
                
                @SuppressWarnings("unchecked")
                List<String> callChain = (List<String>) flow.get("callChain");
                
                if (callChain != null && !callChain.isEmpty()) {
                    html.append(String.format("    <h3>流程 %d</h3>\n", i + 1));
                    html.append("    <div class='flow-diagram'>\n");
                    html.append("        <pre>\n");
                    
                    for (int j = 0; j < callChain.size(); j++) {
                        String indent = "    ".repeat(j);
                        html.append(indent).append("↓\n");
                        html.append(indent).append(callChain.get(j)).append("\n");
                    }
                    
                    html.append("        </pre>\n");
                    html.append("    </div>\n");
                }
            }
        }

        html.append("</div>\n\n");

        return html.toString();
    }

    /**
     * 生成热力图
     */
    private String generateHeatmaps(Map<String, Object> analysisResults) {
        StringBuilder html = new StringBuilder();

        html.append("<div class='section'>\n");
        html.append("    <h2>🔥 代码热力图</h2>\n");
        html.append("    <p>显示代码的修改频率、复杂度、问题密度等</p>\n");

        // 这里可以集成ECharts或D3.js生成热力图
        html.append("    <div class='chart-container'>\n");
        html.append("        <canvas id='heatmapChart'></canvas>\n");
        html.append("    </div>\n");

        html.append("</div>\n\n");

        return html.toString();
    }

    /**
     * 生成详细分析报告
     */
    private String generateDetailedAnalysis(Map<String, Object> analysisResults) {
        StringBuilder html = new StringBuilder();

        html.append("<div class='section'>\n");
        html.append("    <h2>📝 详细分析报告</h2>\n");

        // LLM生成的综合分析
        if (analysisResults.containsKey("comprehensiveReport")) {
            String report = (String) analysisResults.get("comprehensiveReport");
            html.append("    <div class='markdown-content'>\n");
            html.append(convertMarkdownToHtml(report));
            html.append("    </div>\n");
        }

        html.append("</div>\n\n");

        // 页脚
        html.append("<div class='footer'>\n");
        html.append("    <p>© 2025 ZWiki - AI驱动的代码分析系统</p>\n");
        html.append("    <p>Powered by GPT-4 & Spring Boot</p>\n");
        html.append("</div>\n");

        return html.toString();
    }

    // ========== 辅助方法 ==========

    private String getCurrentTimestamp() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    private String simplifyClassName(String fullClassName) {
        int lastDot = fullClassName.lastIndexOf('.');
        return lastDot > 0 ? fullClassName.substring(lastDot + 1) : fullClassName;
    }

    private String getImportanceBadge(int dependencyCount) {
        if (dependencyCount >= 20) {
            return "<span class='badge badge-danger'>极高</span>";
        }
        if (dependencyCount >= 10) {
            return "<span class='badge badge-warning'>高</span>";
        }
        if (dependencyCount >= 5) {
            return "<span class='badge badge-success'>中</span>";
        }
        return "<span class='badge'>低</span>";
    }

    private String convertMarkdownToHtml(String markdown) {
        // 简单的Markdown转HTML（实际应使用专业库）
        return markdown
                .replaceAll("^# (.+)$", "<h1>$1</h1>")
                .replaceAll("^## (.+)$", "<h2>$1</h2>")
                .replaceAll("^### (.+)$", "<h3>$1</h3>")
                .replaceAll("\\*\\*(.+?)\\*\\*", "<strong>$1</strong>")
                .replaceAll("\\*(.+?)\\*", "<em>$1</em>")
                .replaceAll("`(.+?)`", "<code>$1</code>")
                .replaceAll("\\n", "<br>");
    }
}

